package com.example.cheeseerpadmin.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cheeseerpadmin.sys.common.*;
import com.example.cheeseerpadmin.sys.entity.SysPermission;
import com.example.cheeseerpadmin.sys.entity.SysUser;
import com.example.cheeseerpadmin.sys.service.SysPermissionService;
import com.example.cheeseerpadmin.sys.service.SysRoleService;
import com.example.cheeseerpadmin.sys.service.SysUserService;
import com.example.cheeseerpadmin.sys.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/menu")
public class MenuController {
    //注入用于查询permission的service层
    @Autowired
    public SysPermissionService sysPermissionService;
    @Autowired
    public SysUserService sysUserService;
    @Autowired
    public SysRoleService sysRoleService;

    @RequestMapping("/toLoadIndexLeftMenuJson")
    public DataGridView loadIndexLeftMenuJson() {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        //查询符合我们要求的数据，这里指的是 type==menu&&available==1
        queryWrapper.eq("type", Constant.TYPE_MENU);
        queryWrapper.eq("available", Constant.AVAILABLE_TRUE);
        //从session当中获取user，用于下面的if判断
        SysUser user = (SysUser) WebUtils.getSession().getAttribute("user");
        List<SysPermission> list = null;
        if (user.getType().equals(Constant.USER_TYPE_SUPER)) {
            list = sysPermissionService.list(queryWrapper);
        } else {
            Integer uid = user.getId();
            List<Integer> currentUserRoleIds = sysUserService.queryRoleUserByUid(uid);
            //这里使用HashSet集合做的目的其实就是为了能够帮我们进行降重。
            HashSet<Integer> pids = new HashSet<>();
            for (Integer currentUserRoleId : currentUserRoleIds) {
                List<Integer> currentPermissionRoleIds = sysRoleService.queryRolePermissionIdsByRid(currentUserRoleId);
                pids.addAll(currentPermissionRoleIds);
            }

            if (pids.size() > 0) {
                queryWrapper.in("id", pids);
                list = sysPermissionService.list(queryWrapper);
            } else {
                list = new ArrayList<>();
            }
        }

        //这里我们需要做一个菜单的二级展开
        List<TreeNode> treeNodes = new ArrayList<>();
        for (SysPermission sp : list) {
            Integer id = sp.getId();
            Integer pid = sp.getPid();
            String title = sp.getTitle();
            String icon = sp.getIcon();
            String href = sp.getHref();
            Boolean spread = sp.getOpen().equals(Constant.OPEN_TRUE);
            TreeNode treeNode = new TreeNode(id, pid, title, icon, href, spread);
            treeNodes.add(treeNode);
        }

        List<TreeNode> treeNodes1 = TreeNodeBuild.build(treeNodes, 1);

        return new DataGridView(treeNodes1);
    }

    @RequestMapping("/loadMenuLeftTreeJson")
    public DataGridView loadMenuLeftTreeJson(PermissionVo permissionVo) {
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constant.TYPE_MENU);
        List<SysPermission> list = sysPermissionService.list(queryWrapper);
        List<TreeNode> treeNodes = new ArrayList<>();
        for (SysPermission sysPermission : list) {
            TreeNode treeNode = new TreeNode(sysPermission.getId(), sysPermission.getPid(), sysPermission.getTitle(), sysPermission.getOpen() == 1);
            treeNodes.add(treeNode);
        }
        return new DataGridView(treeNodes);
    }

    /**
     * 模糊查询，查询的类型得是menu
     *
     * @param permissionVo
     * @return
     */
    @RequestMapping("/loadAllMenu")
    public DataGridView loadAllMenu(PermissionVo permissionVo) {
        Page<SysPermission> page = new Page<>(permissionVo.getPage(), permissionVo.getLimit());
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        //下面用or()方法连接，标识两个查询到的内容可以并列存在，切记要放在前面。因为or和and的位置不同得到的数据也会不同
        queryWrapper.eq(permissionVo.getId() != null, "pid", permissionVo.getId()).or();
        queryWrapper.eq(permissionVo.getId() != null, "id", permissionVo.getId());

        queryWrapper.eq("type", Constant.TYPE_MENU);
        queryWrapper.like(StringUtils.isNotBlank(permissionVo.getTitle()), "title", permissionVo.getTitle());
        Page<SysPermission> sysPermissionPage = sysPermissionService.page(page, queryWrapper);
        return new DataGridView(sysPermissionPage.getTotal(), sysPermissionPage.getRecords());
    }

    /**
     * 添加菜单
     *
     * @param permissionVo
     * @return
     */
    @RequestMapping("/addMenu")
    public ResultObj addMenu(PermissionVo permissionVo) {
        try {
            permissionVo.setType("menu");
            sysPermissionService.save(permissionVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 获取排序码
     *
     * @return
     */
    @RequestMapping("/loadMenuMaxOrderNum")
    public Map<String, Object> loadMenuMaxOrderNum() {
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        Page<SysPermission> page = new Page<>(1, 1);
        List<SysPermission> list = sysPermissionService.page(page, queryWrapper).getRecords();
        if (list.size() > 0) {
            SysPermission sysPermission = list.get(0);
            Integer ordernum = sysPermission.getOrdernum() + 1;
            map.put("value", ordernum);
            return map;
        } else {
            map.put("value", 1);
            return map;
        }
    }

    /**
     * 更新菜单
     *
     * @param permissionVo
     * @return
     */
    @RequestMapping("/updateMenu")
    public ResultObj updateMenu(PermissionVo permissionVo) {
        try {
            sysPermissionService.updateById(permissionVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteMenuById")
    public ResultObj deleteMenuById(Integer id) {
        try {
            sysPermissionService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 检查菜单节点是否可以直接删除
     *
     * @param id
     * @return
     */
    @RequestMapping("/checkMenuHasChildNode")
    public Map<String, Object> checkMenuHasChildNode(Integer id) {
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", id);
        List<SysPermission> list = sysPermissionService.list(queryWrapper);
        if (list.size() > 0) {
            map.put("value", true);
        } else {
            map.put("value", false);
        }
        return map;
    }
}
